package com.dahua.messageconsumer.service;

import org.springframework.beans.factory.annotation.Value;

import javax.websocket.*;
import java.net.URI;

@ClientEndpoint
public class MyWebSocketClient extends Endpoint {

    private Session session;

    public boolean isOpen = false;

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        this.isOpen = true;
        this.session = session;
        return;
    }

    @Override
    public void onError(Session session, Throwable t) {
        this.isOpen = false;
        System.out.println("失败：" + t.getMessage());
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        this.isOpen = false;
        System.out.println("断开连接");
    }

    public boolean sendMessage(String message) {
        if (this.isOpen && this.session.isOpen()) {
            try {
                this.session.getBasicRemote().sendText(message);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    this.session.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                } finally {
                    this.isOpen = false;
                }
            }
        }
        return false;
    }
}
